package server;

import java.net.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
import javax.swing.*;

import data.*;
/**
 * the server class, mainly making a button and make it multi threaded
 * @author kaidix
 *
 */
public class Server extends JFrame implements ActionListener{
	static JButton button;
	static JFrame frame;
	static JLabel label;
	static boolean keepRunning = true;
	static database.MyIMDB db = new database.MyIMDB();
	public Server(){
		frame = new JFrame();
		label = new JLabel("running ^_^",SwingConstants.CENTER);
		button = new JButton("close server");
		Container container = frame.getContentPane();
		container.setLayout(new GridLayout(2,1));
		container.add(label);
		container.add(button);
		button.addActionListener(this);
		frame.setSize(100,100);
		frame.setVisible(true);
		frame.setLocation(500,500);
		//fame.pack();
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		
	}
	public static void main(String[] args) throws IOException{
		new Server();
		ServerSocket ssocket = new ServerSocket(Information.server_port_number);
		ServerSocket ssocket1 = new ServerSocket(Information.server_port_number+1);
		ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
	    //ServerSocket ssocket = ssocketFactory.createServerSocket(Information.server_port_number);
		//ssocket.bind(new java.net.InetSocketAddress(Information.server_port_number));
		
		while(true){
			System.out.println("waiting");
			Socket s = ssocket.accept();
			Socket s1 = ssocket1.accept();
			System.out.println("connected");
			IOService i = new IOService(s,s1,db);
			Thread t = new Thread(i);
			t.start();
		}
		
	}
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource().equals(button)){
			keepRunning=false;
			frame.dispose();
			db.saveDate();
			System.exit(0);
		}
	}

}
